package com.itsm.xkitsm.liferoot;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itsm.xkitsm.liferoot.ems.ExpressSearchUI;
import com.itsm.xkitsm.liferoot.life.AddActivity;
import com.itsm.xkitsm.liferoot.life.PhoneActivity;
import com.itsm.xkitsm.liferoot.life.weather.Execute_DB;
import com.itsm.xkitsm.liferoot.life.weather.HttpDownloader;
import com.itsm.xkitsm.liferoot.life.weather.Info_city;
import com.itsm.xkitsm.liferoot.life.weather.Info_weather;
import com.itsm.xkitsm.liferoot.life.weather.Instance;
import com.itsm.xkitsm.liferoot.life.weather.JsonParse;
import com.jesgoo.sdk.dsp.DspFailInto;
import com.jesgoo.sdk.dsp.dsp_out.BannerAdDsp;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static com.jesgoo.sdk.dsp.dsp_out.NativeAdDsp.TAG;

public class MainAct extends Activity implements OnClickListener {
	private ImageView img1, img2, img_flashlight, img_express, img_linkman;
	private LinearLayout ll;
	private Animation anim_ll, anim_tv_city;
	private TextView tv_city;
	private boolean isOpen;
	private Camera camera;
	public static Handler hand;
	public static int WHAT = 0x001;
	private String strUrl;
	private String strUrl_cityInfo;
	private String key;
	private Info_weather info;
	private String str_date;

	private TextView tv_onedate, tv_twodate, tv_threedate, tv_fourdate,
			tv_onetemp, tv_twotemp, tv_threetemp, tv_fourtemp;
	private TextView tv_now_temperature, tv_relese_time, tv_onewin, tv_twowin,
			tv_threewin, tv_fourwin, tv_oneweather, tv_twoweather,
			tv_threeweather, tv_fourweather;
	private RelativeLayout adParent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		bind();
		bind_weather();
		ll.startAnimation(anim_ll);
		tv_city.startAnimation(anim_tv_city);

		// ////////////////////////��ȡϵͳʱ��//////////////////////
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日   E");
		Date curDate = new Date(System.currentTimeMillis());// ��ȡ��ǰʱ��
		str_date = formatter.format(curDate);
		// Log.e("ϵͳʱ�䣺", str_date);
		// //////////////////////////////////////////

		// ���ز�ֱ�ӽ�������Ԥ��������
		hand = new Handler() {
			@Override
			public void handleMessage(Message ms) {
				// TODO Auto-generated method stub
				super.handleMessage(ms);

				final String jsonData = (String) ms.obj;
				info = new JsonParse(MainAct.this)
						.parseJson(jsonData); // ����ͼƬ
				Log.e("info.tostring", info.toString());
				if (info!=null){
					setText();
					setIcon(info.getOne_weather());
				}


			}
		};
		if (null != Instance.getInstance().getKey()) {
			key = Instance.getInstance().getKey();
		} else {
			key = "上海";
		}

		download(key);
		initbanner(adParent);

	}

	private void initbanner(ViewGroup viewgroup) {
		viewgroup.removeAllViews();
		final BannerAdDsp bannerAdView = new BannerAdDsp(MainAct.this, new BannerAdDsp.BannerAdDspListener() {

			@Override
			public void onAdReady() {
				Log.d(TAG, "Banner onAdReady");
			}

			@Override
			public void onAdFailed(DspFailInto failInto) {
				Log.d(TAG, "Banner onAdFailed");
			}

			@Override
			public void onAdClick(JSONObject data) {
				Log.d(TAG, "Banner onAdClick");
			}

			@Override
			public void onAdShow(JSONObject data) {
				Log.d(TAG, "Banner onAdShow");
			}

		});
		bannerAdView.loadBanner(MainAct.this, "s19b97df");
		viewgroup.addView(bannerAdView);
	}

	private void setText() {
		tv_onedate.setText(str_date);
		// tv_twodate.setText(info.getTwo_date());
		// tv_threedate.setText(info.getThree_date());
		tv_fourdate.setText(info.getFour_date());

		tv_onetemp.setText(info.getOne_temp());
		tv_twotemp.setText(info.getTwo_temp());
		tv_threetemp.setText(info.getThree_temp());
		tv_fourtemp.setText(info.getFour_temp());

		tv_onewin.setText(info.getOne_win());
		tv_twowin.setText(info.getTwo_win());
		tv_threewin.setText(info.getThree_win());
		tv_fourwin.setText(info.getFour_win());

		tv_oneweather.setText(info.getOne_weather());
		tv_twoweather.setText(info.getTwo_weather());
		tv_threeweather.setText(info.getThree_weather());
		tv_fourweather.setText(info.getFour_weather());
	}

	private void bind_weather() {
		tv_onedate = (TextView) findViewById(R.id.tv_now_date1);
		tv_twodate = (TextView) findViewById(R.id.tv_two_date1);
		tv_threedate = (TextView) findViewById(R.id.tv_three_date1);
		tv_fourdate = (TextView) findViewById(R.id.tv_four_date1);

		tv_onetemp = (TextView) findViewById(R.id.tv_now_temperature_to_temperature1);
		tv_twotemp = (TextView) findViewById(R.id.tv_two_temperature1);
		tv_threetemp = (TextView) findViewById(R.id.tv_three_temperature1);
		tv_fourtemp = (TextView) findViewById(R.id.tv_four_temperature1);

		tv_onewin = (TextView) findViewById(R.id.tv_now_win1);
		tv_twowin = (TextView) findViewById(R.id.tv_two_win1);
		tv_threewin = (TextView) findViewById(R.id.tv_three_win1);
		tv_fourwin = (TextView) findViewById(R.id.tv_four_win1);

		tv_oneweather = (TextView) findViewById(R.id.tv_now_weather1);
		tv_twoweather = (TextView) findViewById(R.id.tv_two_weather1);
		tv_threeweather = (TextView) findViewById(R.id.tv_three_weather1);
		tv_fourweather = (TextView) findViewById(R.id.tv_four_weather1);

	}

	public void download(String key) {
		Log.e(key, key);
		List<Object> data = new Execute_DB(MainAct.this)
				.query_city(key, Execute_DB.city_table);
		String id = ((Info_city) data.get(0)).getCity();
		Log.e("city==", ((Info_city) data.get(0)).toString());
		//参数url化
		String city = null;
		try {
			city = URLEncoder.encode(id, "utf-8");
			strUrl = String.format("http://www.sojson.com/open/api/weather/json.shtml?city=%s",city);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
//		//拼地址
//		strUrl = "http://m.weather.com.cn/data/" + id + ".html";
		Instance.getInstance().setStrUrl(strUrl);
		// ����ҳ�ϵ�������������
		final HttpDownloader http = new HttpDownloader();
		new Thread() {
			public void run() {
				http.download(strUrl);
			};
		}.start();
	}

	private void bind() {
		img1 = (ImageView) findViewById(R.id.img_weather1);
		img2 = (ImageView) findViewById(R.id.img_weather2);
		img_flashlight = (ImageView) findViewById(R.id.img_flashlight);
		img_express = (ImageView) findViewById(R.id.img_express);
		img_linkman = (ImageView) findViewById(R.id.img_linkman);
		tv_city = (TextView) findViewById(R.id.tv_city);
		adParent=findViewById(R.id.ad_parent);
		img_flashlight.setOnClickListener(this);
		img_express.setOnClickListener(this);
		img_linkman.setOnClickListener(this);
		tv_city.setOnClickListener(this);

		ll = (LinearLayout) findViewById(R.id.ll);
		anim_ll = AnimationUtils.loadAnimation(this, R.anim.rotate);
		anim_tv_city = AnimationUtils.loadAnimation(this, R.anim.scale);
		camera = Camera.open();
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_city:
			Intent it = new Intent(MainAct.this, AddActivity.class);
			startActivity(it);
			break;

		case R.id.img_flashlight: {
			Camera.Parameters param = camera.getParameters();
			if (!isOpen) {
				param.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
				img_flashlight.setImageResource(R.drawable.open);
				isOpen = true;
			} else {
				param.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
				img_flashlight.setImageResource(R.drawable.close);
				isOpen = false;
			}
			camera.setParameters(param);
		}
			break;
		case R.id.img_express:
			Intent it1 = new Intent(MainAct.this,
					ExpressSearchUI.class);
			startActivity(it1);
			break;
		case R.id.img_linkman:
			Intent it2 = new Intent(MainAct.this,
					PhoneActivity.class);
			startActivity(it2);
			break;
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		surfaceDestroyed();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		surfaceDestroyed();
		if (retrieveBroadcast != null) {
			unregisterReceiver(retrieveBroadcast);
		}
	}

	public void surfaceDestroyed() {
		if (null != camera) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();



	}

	public void setIcon(String str_weather) {
		if (str_weather.contains("转")) {
			String[] temp = str_weather.split("转");
			for (int i = 0; i < temp.length; i++) {
				if (temp[i].contains("晴")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.qing);

							break;

						case 1:
							img2.setImageResource(R.drawable.qing);
							break;
					}
				}

				if (temp[i].contains("多云")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.duoyun);

							break;

						case 1:
							img2.setImageResource(R.drawable.duoyun);
							break;
					}
				}

				if (temp[i].contains("雾") || temp[i].contains("霾")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.wu1);
							img2.setImageResource(R.drawable.wu2);
							break;

						case 1:
							img1.setImageResource(R.drawable.wu1);
							img2.setImageResource(R.drawable.wu2);
							break;
					}
				}

				if (temp[i].contains("雪")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.xue);

							break;

						case 1:
							img2.setImageResource(R.drawable.xue);
							break;
					}
				}
				if (temp[i].contains("雨")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.yu);

							break;

						case 1:
							img2.setImageResource(R.drawable.yu);
							break;
					}
				}

				if (temp[i].contains("雨夹雪")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.yujiaxue);

							break;

						case 1:
							img2.setImageResource(R.drawable.yujiaxue);
							break;
					}
				}
				if (temp[i].contains("阴")) {
					switch (i) {
						case 0:
							img1.setImageResource(R.drawable.ying);

							break;

						case 1:
							img2.setImageResource(R.drawable.ying);
							break;
					}
				}

			}
		} else {
			if (str_weather.contains("晴")) {
				img1.setImageResource(R.drawable.qing);
				img2.setImageResource(R.drawable.qing);
			} else if (str_weather.contains("多云")) {
				img1.setImageResource(R.drawable.duoyun);
				img2.setImageResource(R.drawable.duoyun);
			} else if (str_weather.contains("阴")) {
				img1.setImageResource(R.drawable.ying);
				img2.setImageResource(R.drawable.ying);
			} else if (str_weather.contains("雾") && str_weather.contains("霾")) {
				img1.setImageResource(R.drawable.wu1);
				img2.setImageResource(R.drawable.wu2);
			} else if (str_weather.contains("雨")) {
				img1.setImageResource(R.drawable.yu);
				img2.setImageResource(R.drawable.yu);
			} else if (str_weather.contains("雪")) {
				img1.setImageResource(R.drawable.xue);
				img2.setImageResource(R.drawable.xue);
			} else if (str_weather.contains("雨加雪")) {
				img1.setImageResource(R.drawable.yujiaxue);
				img2.setImageResource(R.drawable.yujiaxue);
			}
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		if (retrieveBroadcast == null) {
			retrieveBroadcast = new RetrieveBroadcast();
			registerReceiver(retrieveBroadcast, new IntentFilter(CHANGECITY));
		}
	}


	private RetrieveBroadcast retrieveBroadcast;
	public static final String CHANGECITY = "Change_City";

	private class RetrieveBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			key = Instance.getInstance().getKey();
			if (null != key) {
				download(key);
				tv_city.setText(key);
			}
		}
	}

}
